import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, classification_report
from imblearn.over_sampling import SMOTE
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger()

logger.info("1. 加载数据")
data = pd.read_excel('homework/covid-19 symptoms dataset.xlsx')

# 2. 数据预处理
logger.info("2. 数据预处理")
X = data.drop('infectionProb', axis=1)  # 特征
y = data['infectionProb']  # 标签

# 特征缩放
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 处理类别不平衡
sm = SMOTE(random_state=42)
X_res, y_res = sm.fit_resample(X_scaled, y)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_res, y_res, test_size=0.3, random_state=42)
logger.info(f"训练集大小: {X_train.shape}, 测试集大小: {X_test.shape}")

# 3. 创建和调优逻辑回归模型
logger.info("3. 模型调优")
param_grid = {
    'C': [0.01, 0.1, 1, 10],
    'solver': ['liblinear', 'lbfgs'],
}

grid_search = GridSearchCV(LogisticRegression(class_weight='balanced'), param_grid, cv=5)
grid_search.fit(X_train, y_train)

best_model = grid_search.best_estimator_
logger.info(f"最佳参数: {grid_search.best_params_}")

# 4. 训练最佳模型
logger.info("4. 训练最佳模型")
best_model.fit(X_train, y_train)

# 5. 模型评估
logger.info("5. 模型评估")
y_pred = best_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
logger.info(f'模型准确率: {accuracy:.4f}')
logger.info(f'分类报告:\n{classification_report(y_test, y_pred)}')

logger.info("实验完成")
